<template>
  <div class="edit-form">
    <el-dialog
      title="编辑权限组"
      :visible.sync="editDialogFormVisible"
    >
      <el-form
        :model="editPermissionForm"
        :rules="editPermissionFormRules"
        ref="editPermissionFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="用户名"
          prop="title"
        >
          <el-input v-model="editPermissionForm.title"></el-input>
        </el-form-item>
        <el-form-item label="权限分配">
          <!-- 树形表格 -->
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[1]"
            :default-checked-keys="checkedArray"
            auto-expand-parent
          ></el-tree>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="$emit('close')">取 消</el-button>
        <el-button
          type="primary"
          @click="editPermissionList"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { detail as getEdit, update as editPermission } from '@/api/base/permissions.js'
import { list as getPermissions } from '@/api/base/menus'
export default {
  name: 'PermissionGroupsApiAdd',
  props: {
    permissions: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      editDialogFormVisible: false,
      editPermissionForm: {
        id: this.permissions.id,
        title: this.permissions.title,
        permissions: [] // 选中的权限id
      },
      editPermissionFormRules:
      {
        title: [{ required: true, message: '请输入用户名' }]
      },
      treeData: [], // 权限
      treeProps: {
        children: 'childs', // 数据列表通过childs实现嵌套关系
        label: 'title' // 需要展示的字段
      },
      permissionsKey: [], // 默认选中的节点数组,
      checkedArray: [] // 展示选中的数组
    }
  },
  created () {
    this.getPermissionsList()
    this.getEditList()
  },
  methods: {
    // 获取权限树数据列表
    async getPermissionsList () {
      const { data } = await getPermissions()
      // console.log(data)
      // 将返回数据中的points换成childs
      const str = JSON.stringify(data)
      // console.log(str)
      const newStr = str.replace(/points/g, 'childs')
      const newData = JSON.parse(newStr)
      const results = {
        id: 1,
        title: '系统菜单和页面权限点',
        childs: [...newData]
      }
      // console.log(results)
      this.treeData.push(results)
      // 递归方法
      this.getLefkey(results, this.permissionsKey)
      // console.log(this.permissionsKey)
      this.editPermissionVisible = true
    },
    // 获取角色下所有的三级权限的id并且保存到permissionsKey数组中
    getLefkey (node, arr) {
      // 如果是三级节点,返回处理好的id即可
      if (!node.childs) {
        // console.log(node, arr)
        return arr.push(node.id)
      }
      // 如果存在childs,说明不是三级节点,继续使用遍历的方法
      node.childs.forEach(item => {
        this.getLefkey(item, arr)
      })
    },
    // 编辑弹框打开后,获取该角色的权限
    async  getEditList () {
      const { data } = await getEdit(this.editPermissionForm)
      const newTreeData = []
      setTimeout(() => {
        data.permissions.forEach((permission) =>
          this.permissionsKey.forEach((item) => {
            if (permission === item) {
              newTreeData.push(permission)
            }
          })
        )
        // 因为:default-expanded-keys 识别不了 后面有  __ob__:Observer 的数组，导致标记无法被渲染
        // 所以使用JSON.parse(JSON.stringify(newTreeData))转换一下
        this.checkedArray = JSON.parse(JSON.stringify(newTreeData))
        // 这里因为有选中项显示延迟的情况，所以在这里加上下方代码，使选中项被赋值后，弹框显示
        this.editDialogFormVisible = true
      }, 100)
    },
    // 编辑功能实现
    async  editPermissionList () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      this.editPermissionForm.permissions = keys
      await editPermission(this.editPermissionForm)
      this.editDialogFormVisible = false
      this.$emit('close')
    }
  }
}
</script>

<style>
</style>
